/*********************************************添加宝宝表单验证开始********************************************************/

// babyName;  姓名
function isName (name) {
    var pattern = /^[\u4E00-\u9FA5]{1,6}$/;
    return pattern.test(name);
}
//数字验证
function isNumber(number) {
    var pattern =/^[0-9]*$/ ;
    return pattern.test(number);
}
//整数或小数
function isFloatAdnNUmber(number) {
    var pattern =/^[0-9]+([.]{1}[0-9]+){0,1}$/ ;
    return pattern.test(number);
}
// emage;  年龄
function isAge (emage) {
    var pattern = /^(?:[1-9]?\d|100)$/;
    return pattern.test(emage);
}

// 宝宝表单验证函数
function babyFormCheck() {

    var result = "";

    // 判断头像
    if($.trim($(".strPhoto").val()).length == 0){
        result += "fail";
        $(".tipstrPhoto").html("*请上传头像！").css("color", "red");
    } else {
        // 验证通过
        $(".tipstrPhoto").html("√").css("color", "green");
    }

    // 判断名字
    if ($.trim($(".babyName").val()) == null) {
        result += "fail";
        $(".tipBabyName").html("*名字不能为空！").css("color", "red");
    } else {
        if (isName($.trim($(".babyName").val())) == false) {
            result += "fail";
            $(".tipBabyName").html("*名字格式不正确！").css("color", "red");
        } else {
            // 验证通过
            $(".tipBabyName").html("√").css("color", "green");
        }
    }
    //判断档案编号
    if($.trim($(".fileNo").val()).length == 0){
        result += "fail";
        $(".tipFileNo").html("*档案编号不能为空！").css("color", "red");
    }else {
        if (isNumber($.trim($(".fileNo").val())) == false) {
            result += "fail";
            $(".tipFileNo").html("*档案编号格式不正确！").css("color", "red");
        } else {
            // 验证通过
            $(".tipFileNo").html("√").css("color", "green");
        }
}
    //判断年龄
    if($.trim($(".babyAge").val()).length == 0){
        result += "fail";
        $(".tipBabyAge").html("*年龄不能为空！").css("color", "red");
    }else {
            // 验证通过
            $(".tipBabyAge").html("√").css("color", "green");
        }
    //判断体重
    if($.trim($(".babyWeight").val()).length == 0){
        result += "fail";
        $(".tipBabyWeight").html("*必填！").css("color", "red");
    }else if(isFloatAdnNUmber($.trim($(".babyWeight").val())) == false)
    {
        result += "fail";
        $(".tipBabyWeight").html("*格式不正确！").css("color", "red");
    }else if($.trim($(".babyWeight").val()) >50 || $.trim($(".babyWeight").val()) == 0){
        result += "fail";
        $(".tipBabyWeight").html("*请输入正确的体重!(单位kg)").css("color", "red");
    }
    else {
        // 验证通过
        $(".tipBabyWeight").html("√").css("color", "green");
    }
    //判断身高
    if($.trim($(".babyHeight").val()).length == 0){
        result += "fail";
        $(".tipBabyHeight").html("*必填！").css("color", "red");
    }else if (isFloatAdnNUmber($.trim($(".babyHeight").val())) == false)
    {
        result += "fail";
        $(".tipBabyHeight").html("*格式不正确！").css("color", "red");
    }
    else if($.trim($(".babyHeight").val()) >130 || $.trim($(".babyHeight").val()) == 0){
        result += "fail";
        $(".tipBabyHeight").html("*请输入真确的身高!(单位cm)").css("color", "red");
    }else {
        // 验证通过
        $(".tipBabyHeight").html("√").css("color", "green");
    }
    //判断出身日期
    if($.trim($(".babybirthday").val()).length == 0){
        result += "fail";
        $(".tipBabybirthday").html("*必填！").css("color", "red");
    } else if($.trim($(".babybirthday").val()).length != 0){
        var birth = $('.babybirthday').val();
        var birthYear = parseInt($('.babybirthday').val().substring(0, 4));
        var date = new Date();
        var nowYear = date.getFullYear();
        var nowDate = timeStampToDate(date.getTime());
        var age = nowYear - birthYear;
        if (birth > nowDate || age < 0 || age > 100) {
            result += "fail";
            $(".tipBabybirthday").html("*请选择正确的日期！").css("color", "red");
        } else if(age == 0){
            $(".babyAge").val("未满1");
            $(".tipBabybirthday").html("√").css("color", "green");
        }else {
            // 验证通过
            $(".babyAge").val(age);
            $(".tipBabybirthday").html("√").css("color", "green");
        }
    }
    //录入时间

    /*if($.trim($(".infoInputDate").val()).length == 0){
        result += "fail";
        $(".tipInfoInputDate").html("*录入时间不能为空！").css("color", "red");
    } else {
        // 验证通过
        $(".tipInfoInputDate").html("√").css("color", "green");
    }*/

    // 判断所有验证是否通过
    if (result != "") {
        return false;
    } else {
        return true;
    }

}
//根据出生日期计算年龄
function countAge(){
    var birth = $('.babybirthday').val() ;
    var birthYear = parseInt($('.babybirthday').val().substring(0,4));
    var date = new Date();
    var nowYear = date.getFullYear();
    var nowDate = timeStampToDate(date.getTime());
    var age = nowYear-birthYear;
    if(age<0 || age>100 || birth > nowDate){
        $(".tipBabybirthday").html("*请选择正确的日期！").css("color","red");
        $(".babyAge").val("");
    }else if(birth > nowDate){

    }else if(age == 0) {
        $(".babyAge").val("未满1");
    }else {
        $(".babyAge").val(age);
        $(".tipBabybirthday").html("√").css("color", "green");
    }
}

// 时间戳转换成日期格式
function timeStampToDate(timeStamp) {
    if (timeStamp == null) {
        return null;
    } else {
        var date = new Date(timeStamp);
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = (date.getDate()+1 < 10 ? '0'+(date.getDate()) : date.getDate());
        // h = date.getHours() + ':';
        // m = date.getMinutes() + ':';
        // s = date.getSeconds();
        return Y+M+D;
    }
}

// 上传图片并回显示
$(".addBabyPhoto").bind ('change', function() {
    var fordate = new FormData();
    var fils = $(".addBabyPhoto").get(0).files[0];
    fordate.append('pic', fils);
    var result = uploadfile("addBabyPhoto");
    if (result.code == 0) {
        $(".imagePhoto").attr({'src': result.data});
        $(".strPhoto").val(result.data);
        console.log("图片上传成功！");
    } else {
        console.log("图片上传失败！");
    }
});



// 添加宝宝信息
$('#submitAddBabyBtn').on('click', function() {
    if (babyFormCheck()) {
        $.ajax({
            type: "POST",
            url: "/babyInfoController/addBabyInfo",
            dataType: "json",
            data: $('#babyForm').serialize(),
            success: function (data) {
                if (data.result == "success") {
                    alert("添加成功！");
                    window.location.href = "/babyInfoController/findBaby";
                } else {
                    alert("添加失败！");
                }
            },
            error: function () {
                alert("发送请求失败！");
            }
        });
    } else {
        alert("您输入的信息有误，请检查红色字段。");
    }
});

//删除宝宝信息
function delBabyBtn(babyId) {
    $("#delBabyConfirm").modal({
        onConfirm: function() {
            $.ajax({
                type: "GET",
                url: "/babyInfoController/delBabyInfo?babyId=" + babyId,
                dataType: "json",
                success: function (data) {
                    if (data.result == "success") {
                        alert("删除成功！");
                        window.location.reload();
                    } else {
                        alert("删除失败！");
                    }
                },
                error: function () {
                    alert("发送请求失败！");
                }
            });
        }
    });
}

// 获得单个宝宝信息
function editBabyBtn(babyId) {
    $("#submitAddBabyBtn").hide();
    $.ajax({
        type: "GET",
        url: "/babyInfoController/findOneBabyInfo?babyId=" + babyId,
        dataType: "json",
        success: function (data) {
            /****************查询出来显示在查看页面标签中*****************/
            //唯一标识
            $(".babyId").val(data.bb.babyId);
            // 头像
            $(".imagePhoto").attr("src", data.bb.babyPhoto);
            $(".strPhoto").val(data.bb.babyPhoto);
            // 纸质档案编号
            $(".fileNo").val(data.bb.fileNo);
            // 姓名
            $(".babyName").val(data.bb.babyName);
            // 性别
            if (data.bb.babySex == 1) {
                $(".babySex:eq(0)").attr("checked", "checked");
            } else {
                $(".babySex:eq(1)").attr("checked", "checked");
            }
            // 年龄
            $(".babyAge").val(data.bb.babyAge);
            // 体重
            $(".babyWeight").val(data.bb.babyWeight);
            // 身高
            $(".babyHeight").val(data.bb.babyHeight);
            // 出生日期
            $(".babybirthday").datepicker('setValue', data.bb.babybirthday);
            //是否早产
            if (data.bb.premature == 1) {
                $(".premature:eq(0)").attr("checked", "checked");
            } else {
                $(".premature:eq(1)").attr("checked", "checked");
            }
            // 录入时间
            $(".infoInputDate").datepicker('setValue', data.bb.infoInputDate);
            // 喂养史
            $(".feedHistory").val(data.bb.feedHistory);
            // 过敏史
            $(".allergyHistory").val(data.bb.allergyHistory);
            // 病史
            $(".sickHistory").val(data.bb.sickHistory);
            // 备注
            $(".babyNote").val(data.bb.babyNote);
            //调理次数
            $(".serviceCount").val(data.serviceCount);
        },
        error: function () {
            alert("发送请求失败！");
        }
    });
}


 //修改宝宝信息
function updateBabyBtn() {
    if (confirm("您确定更新当前宝宝的信息？")) {
        // 前端验证
        if (babyFormCheck()) {
            // 发送请求
            $.ajax({
                type: "POST",
                url: "/babyInfoController/updateBabyInfo",
                dataType: "json",
                data: $('#babyForm').serialize(),
                success: function (data) {
                    if (data.result == "success") {
                        alert("更新成功！");
                        window.location.reload();
                    } else {
                        alert("更新失败！");
                    }
                },
                error: function () {
                    alert("发送请求失败！");
                }
            });
        } else {
            alert("您输入的信息有误，请检查红色字段。");
        }
    }
}

//根据出生日期获取年龄
function babyAge(){
    var date =new date();
    var year =$(".babybirthday").datepicker('setValue', data.bb.babybirthday);
}

// 给按钮设置（取消，关闭）点击刷新网页
$('.clearForm').on('click', function() {
    window.location.reload();
});

// 点击头像
function showPhotoFun (babyId) {
    $.ajax({
        type: "GET",
        url: "/babyInfoController/findOneBabyInfo?babyId=" + babyId,
        dataType: "json",
        success: function (data) {
            $(".imagePhoto").attr({'src': data.bb.babyPhoto});
        },
        error: function () {
            alert("发送请求失败！");
        }
    });
}

// 影藏修改按钮
function hideBtn() {
    $("#updateBtn").hide();
}

// 模糊查询
$("#searchBtn").on("click", function () {
    var type = $("#searchType").val();
    var content = $("#searchContent").val();
    if (content === null || content === undefined || content === '' || content.length === 0) {
        alert("请输入查询条件！");
        return false;
    } else {
        var data = new FormData();
        $.ajax({
            type: 'POST',
            data: {"type": type, "content": content},
            url: "/babyInfoController/searchBabyInfo",
            cache: false,
            success: function (data) {
                // document.write(data);
                $("table").remove();
                // $(".paging").remove();
                var $data = $(data); // 将整个文档转化为jquery对象
                var content = $data.find("table");
                $(".tableDiv").append(content);
            },
            error: function () {
                alert("请求失败！");
            }
        });
    }
});

// 模糊查询
$("#searchBtn").on("click", function () {
    var type = $("#searchType").val();
    var content = $("#searchContent").val();
    if (content === null || content === undefined || content === '' || content.length === 0) {
        alert("请输入查询条件！");
        return false;
    } else {
        window.location.href = "/babyInfoController/searchBabyInfo?type=" + type + "&content=" + content;
    }
});
